#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/syscall.h>
#include <errno.h>
#include "../glob.h"

#define gettid() syscall(__NR_gettid)

pthread_mutex_t mutex;
pthread_cond_t 	notEmpty ;

int thread_routine(void * args)
{
	
	
	//printf("-------------------1\n");
	//printf("-------------------2\n");
	//sleep(10);
	DEBUG("thread id %d",gettid());
	
	while(1)
	{
		DEBUG("***");	
		//pthread_mutex_lock(&mutex);
		pthread_cond_wait(&notEmpty,&mutex);
		//pthread_mutex_unlock(&mutex);
		DEBUG("***\n");
	}
	
#if 0	
	pthread_mutex_lock(&mutex);
	pthread_cond_wait(&notEmpty,&mutex);
	pthread_mutex_unlock(&mutex);
	
	DEBUG("***");
#endif	
	return 0;
}

int check_thread_exist(pthread_t thread_id)
{
	int kill_rc = pthread_kill(thread_id,0);

	if(kill_rc == ESRCH)
	DEBUG("the specified thread did not exists or already quit");
	else if(kill_rc == EINVAL)
	DEBUG("signal is invalid");
	else
	DEBUG("the specified thread is alive");

	return 0;
}


int main(int argc, char* argv[])
{
	pthread_t td;
	int result;
	int kill_rc;
	
	
	pthread_mutex_init(&mutex,NULL);
	pthread_cond_init(&notEmpty,NULL);	
	
	check_thread_exist(td);
	pthread_create(&td, NULL, (void*)thread_routine, NULL);
	DEBUG("main***td=%08x",td);
	check_thread_exist(td);
	sleep(5);
	pthread_mutex_lock(&mutex);
	pthread_cond_signal(&notEmpty);
	pthread_mutex_unlock(&mutex);
	
	DEBUG("main***");
	
	sleep(5);
	pthread_mutex_lock(&mutex);
	pthread_cond_signal(&notEmpty);
	pthread_mutex_unlock(&mutex);
	DEBUG("main***");
	check_thread_exist(td);
	
	pthread_join(td, NULL);
	check_thread_exist(td);
	
	pthread_cond_destroy(&notEmpty);
	pthread_mutex_destroy(&mutex);

	return 0;	
}